<script setup lang="tsx">
import { PropType, reactive, watch, ref, unref } from 'vue'
import { cloneDeep } from 'lodash-es'

import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { getMenuTreeListApi } from '@/api/system/menuApi'
import { getListApi } from '@/api/system/permission'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const switchComponentProps = {
  activeValue: 1,
  inactiveValue: 0
}

const formSchema = reactive<FormSchema[]>([
  {
    field: 'type',
    label: '菜单类型',
    component: 'RadioButton',
    value: 0,
    colProps: {
      span: 24
    },
    componentProps: {
      options: [
        {
          label: '目录',
          value: 0
        },
        {
          label: '菜单',
          value: 1
        }
      ],
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val === 1) {
            setSchema([
              {
                field: 'component',
                path: 'componentProps.disabled',
                value: false
              }
            ])
            setValues({
              component: unref(cacheComponent)
            })
          } else {
            setSchema([
              {
                field: 'component',
                path: 'componentProps.disabled',
                value: true
              }
            ])

            if (formData.parentId === 0) {
              setValues({
                component: '#'
              })
            } else {
              setValues({
                component: '##'
              })
            }
          }
        }
      }
    }
  },
  {
    field: 'parentId',
    label: '父级菜单',
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'id',
      props: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      highlightCurrent: true,
      expandOnClickNode: false,
      checkStrictly: true,
      checkOnClickNode: true,
      clearable: true,
      on: {
        change: async (val: number) => {
          const formData = await getFormData()
          if (val && formData.type === 0) {
            setValues({
              component: '##'
            })
          } else if (!val && formData.type === 0) {
            setValues({
              component: '#'
            })
          } else if (formData.type === 1) {
            setValues({
              component: unref(cacheComponent) ?? ''
            })
          }
        }
      }
    },
    optionApi: async () => {
      const { data } = await getMenuTreeListApi()
      const menuList = [
        {
          id: 0,
          name: '主类目',
          children: data
        }
      ]
      return menuList
    },
    value: 0
  },
  {
    field: 'meta.title',
    label: '菜单名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'component',
    label: '组件路径',
    component: 'Input',
    value: '#',
    componentProps: {
      disabled: true,
      placeholder: '#为顶级目录，##为子目录',
      on: {
        change: (val: string) => {
          cacheComponent.value = val
        }
      }
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'name',
    label: '组件名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'meta.icon',
    label: '图标',
    component: 'IconPicker'
  },
  {
    field: 'path',
    label: '路径',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'meta.activeMenu',
    label: '高亮菜单',
    component: 'Input'
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '禁用',
          value: 0
        },
        {
          label: '启用',
          value: 1
        }
      ]
    },
    value: 1
  },
  {
    field: 'permission',
    label: '按钮权限',
    component: 'CheckboxGroup',
    colProps: {
      span: 24
    },
    componentProps: {
      props: {
        value: 'id'
      }
    },
    optionApi: async () => {
      const { data } = await getListApi()
      data.forEach((item: any) => {
        item.id = '' + item.id
      })
      return data
    }
  },
  {
    field: 'meta.hidden',
    label: '是否隐藏',
    component: 'Switch',
    componentProps: switchComponentProps
  },
  {
    field: 'meta.alwaysShow',
    label: '是否一直显示',
    component: 'Switch',
    componentProps: switchComponentProps
  },
  {
    field: 'meta.noCache',
    label: '是否清除缓存',
    component: 'Switch',
    componentProps: switchComponentProps
  },
  {
    field: 'meta.breadcrumb',
    label: '是否显示面包屑',
    component: 'Switch',
    componentProps: switchComponentProps
  },
  {
    field: 'meta.affix',
    label: '是否固定在标签页',
    component: 'Switch',
    componentProps: switchComponentProps
  },
  {
    field: 'meta.noTagsView',
    label: '是否隐藏标签页',
    component: 'Switch',
    componentProps: switchComponentProps
  },
  {
    field: 'meta.canTo',
    label: '是否可跳转',
    component: 'Switch',
    componentProps: switchComponentProps
  }
])

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate()
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const cacheComponent = ref('')

watch(
  () => props.currentRow,
  (value) => {
    if (!value) return
    const currentRow = cloneDeep(value)
    cacheComponent.value = currentRow.type === 1 ? currentRow.component : ''
    if (currentRow.parentId === 0) {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    } else {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: false
        }
      ])
    }

    if (currentRow.type === 1) {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: false
        }
      ])
    } else {
      setSchema([
        {
          field: 'component',
          path: 'componentProps.disabled',
          value: true
        }
      ])
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form @register="formRegister" :schema="formSchema" />
</template>
